const digest = require("sip/digest");
const sip = require("sip");
const log4js = require('../../../utils/logUtils');
const logger = log4js.getLogger('sip');
const sipUtils = require('../../../utils/sipUtils');
const config = require("../../../db/config");
const settingModel = require("../../../model/setting");

/**
 * register 消息回应
 * @type {{handle()}}
 */
module.exports={
    generate(rq){
        // fix有的摄像头这里uri多一组sip:
        rq.uri = rq.uri.replace('sip:sip:', 'sip:');
        let uri = rq.headers.to.uri;
        // 生成用户信息
        let userinfo = {
            password: settingModel.cache.sip_command_password,
            session: {
                realm: settingModel.cache.server_realm
            }
        };

        let authorized = false;
        let ret;

        if (config.sip.authorize) {
            if (!rq.headers['authorization']) {
                // 第一次的注册请求
                ret = digest.challenge(userinfo.session, sip.makeResponse(rq, 401, 'Unauthorized'));
            } else {
                // 第2次的注册请求
                if (rq.headers.authorization) {
                    userinfo.session = {
                        realm: settingModel.cache.server_realm,
                        nonce: sipUtils.trim(rq.headers.authorization[0].nonce)
                    };
                }
                // 去掉一些没用的引号
                if (rq && rq.headers && rq.headers.authorization) {
                    rq.headers.authorization[0].username = sipUtils.trim(rq.headers.authorization[0].username);
                    rq.headers.authorization[0].realm = sipUtils.trim(rq.headers.authorization[0].realm);
                    rq.headers.authorization[0].nonce = sipUtils.trim(rq.headers.authorization[0].nonce);
                    rq.headers.authorization[0].uri = sipUtils.trim(rq.headers.authorization[0].uri);
                    rq.headers.authorization[0].response = sipUtils.trim(rq.headers.authorization[0].response);
                    rq.headers.authorization[0].cnonce = sipUtils.trim(rq.headers.authorization[0].cnonce);
                }
                if (digest.authenticateRequest(userinfo.session, rq, {
                    user: sipUtils.trim(rq.headers.authorization[0].username),
                    password: userinfo.password
                })) {
                    authorized = true;
                } else {
                    ret = digest.challenge(userinfo.session, sip.makeResponse(rq, 401, 'Unauthorized'));
                    ret.headers.via[0]['received'] = null;
                    ret.headers.expires = rq.headers.expires;
                }
            }
        } else {
            authorized = true;
        }
        if (authorized) {
            logger.info(`成功授权:uri = ${uri}`);
            // 完成授权
            ret = sip.makeResponse(rq, 200, 'Ok');
            ret.headers.to.params.tag = sipUtils.rstring();
        }
        return ret;
    }
}
